// 属性
var attr_data =
    [
        '尺寸', '金重', '机芯', '适用', '净含量', '包装', '款式', '口味', '产地', '种类', '内存', '套餐', '出行日期', '出行人群', '入住时段', '房型', '介质', '开本', '版本', '类型（例如实体票,电子票）',
        '有效期', '乘客类型', '伞面尺寸', '儿童/青少年床尺寸', '内裤尺码', '出发日期', '剩余保质期', '佛珠尺寸', '克重', '型号', '大小', '大小描述', '功率', '吉祥图案', '圆床尺寸', '奶嘴规格', '娃娃尺寸',
        '安全套规格', '宠物适用尺码', '布尿裤尺码', '帽围', '床品尺寸', '戒圈', '户外帽尺码', '户外手套尺码', '手镯内径', '方形地毯规格', '毛色', '洗车机容量', '珍珠直径', '珍珠颜色', '瓷砖尺寸（平方毫米）',
        '线号', '床垫厚度', '床垫规格', '床尺寸', '座垫套件数量', '建议身高（尺码）', '画布尺寸', '画框尺寸', '皮带长度', '窗帘尺寸（宽X高)', '笔芯颜色', '粉粉份量', '纸张规格', '线材长度', '线长',
        '组合', '绣布CT数', '胸围尺码', '胸垫尺码', '自定义项', '色温', '花束直径', '花盆规格', '蛋糕尺寸', '袜子尺码', '规格尺寸', '规格（粒/袋/ml/g）', '贵金属成色', '车用香水香味', '适用年龄',
        '适用床尺寸', '适用户外项目', '适用范围', '适用规格', '遮阳挡件数', '邮轮房型', '钓钩尺寸', '钻石净度', '钻石重量', '钻石颜色', '链子长度', '锅具尺寸', '锅身直径尺寸', '镜子尺寸', '镜片适合度数',
        '镶嵌材质', '长度', '防潮垫大小', '雨刷尺寸', '鞋码', '鞋码（内长）', '香味', '颜色', '尺码', '上市时间', '容量', '系列', '规格'
    ];
//图片上传
$(function () {
    $("#portrait").wrap("<form id='upload_portrait' action='/product/upload-image' method='post' enctype='multipart/form-data'></form>");
    $("#portrait").change(function () {
        var index = layer.load(2, {
            shade: [0.5,'#fff'] //0.1透明度的白色背景
        });
        $("#upload_portrait").ajaxSubmit({
            dataType: 'json',
            beforeSend: function () {
            },
            uploadProgress: function (event, position, total, percentComplete) {
            },
            success: function (data) {
                if (data.code === 200) {
                    var result = data.result;
                    var img = "http://xianyongta.oss-cn-shanghai.aliyuncs.com/files/" + result.pic;
                    $('.portrait_show').html("<div class='swiper-slide'><img  height='150px' id='portrait_show' src=" + img + "></div>")

                } else {
                    layer.open({
                        content: data.message,
                        btn: ['确认'],
                        shadeClose: false,
                    });
                }
                layer.close(index);
            },
            error: function (xhr) {
                btn_portrait.html("上传失败");
                bar.width('0');
                files_portrait.html(xhr.responseText);
                layer.close(index);
            }
        });
    });
    // 上传凭证
    $("#voucher").wrap("<form id='upload_voucher' action='/product/upload-image' method='post' enctype='multipart/form-data'></form>");
    $("#voucher").change(function () {
        var index = layer.load(2, {
            shade: [0.5,'#fff'] //0.1透明度的白色背景
        });
        $("#upload_voucher").ajaxSubmit({
            dataType: 'json',
            beforeSend: function () {
            },
            uploadProgress: function (event, position, total, percentComplete) {
            },
            success: function (data) {
                if (data.code === 200) {
                    var result = data.result;
                    var img = "http://xianyongta.oss-cn-shanghai.aliyuncs.com/files/" + result.pic;
                    $('.voucher_show').html("<div class='swiper-slide'><img  height='150px' id='voucher_show' src=" + img + "></div>")

                } else {
                    layer.open({
                        content: data.message,
                        btn: ['确认'],
                        shadeClose: false,
                    });
                    return false;
                }
                layer.close(index);
            },
            error: function (xhr) {
                btn_voucher.html("上传失败");
                bar.width('0');
                files_voucher.html(xhr.responseText);
            }
        });
    });
});
// -----------上传图片开始--------------
var panel = ".banner_modify_panel ";
$(document).ready(function () {
    if (product_image_list) {
        var banners = new Array();
        var fnSort = function (a, b) {
            if (a.sort != undefined && b.sort != undefined) {
                return a.sort - b.sort;
            }
        }
        for (var i in product_image_list) {
            banners[i] = product_image_list[i];
        }
        var sort_banners = banners.sort(fnSort),
            rows = sort_banners,
            row = {},
            max_idx = 0,
            i = 0,
            idx = 0;
        //加载图片
        for (var i in rows) {
            row = rows[i];
            idx = row.sort;
            //console.log(row);
            if (idx > max_idx) {
                max_idx = idx;
            }
            var jq_img_li = AddImage(idx, row.img_url, 0);
            jq_img_li.removeClass("hidden");
        }
    }

    max_idx = 0;
    //添加图片的点击事件
    idx = max_idx + 1;
    $(document).on('click', $(panel + " .goods_image .add"), function(){
        AddImage(idx, "", "");
        idx++;
    });
    //拖动
    var ele_parent = panel + ".goods_image ";
    $(ele_parent).dragsort({
        //itemSelector: ".draglist",
        dragSelector: ".real_images",
        dragBetween: true,
        dragEnd: function () {
            return true;
        },
        dragSelectorExclude: ".input_file"
    });
    $(panel + ".panel_reset").bind("click", function () {
        location.reload();
    });
});

AddImage = function (idx, val, default_status) {
    var ele_parent = $(panel).find(".goods_image"),
        ele_li = ele_parent.find("li:last"),
        new_ele = '<li class="real_images hidden draglist" idx='+idx+' draggable="true" style="cursor:move" >'
    var image_last = panel + ".goods_image " + ".real_images:last ";
    if ($(image_last).hasClass('hidden')) {
        return true;
    }
    style =  'style="color:black"';
    if(default_status){
        var style = 'style="color:#88CE20"';
    }
    new_ele += '<a draggable="false" ' + ' target="_blank" >'
        + '<img data-action="zoom" draggable="false" src="' + val + '" alt="" name="images_preview">'
        + '</a>'
        + '<input type="text" class="hidden default_input" name="default[' + idx + ']" value="' + default_status + '">'
        + '<input type="text" class="hidden" name="images[' + idx + ']" value="' + val + '">';
    new_ele += '<p class="main_img"><span style="width: 100%" class="delete">删除</span></p></li>';
    new_jq_ele = $(new_ele);
    new_jq_ele.find(".delete").on("mousedown", function () {//删除图片事件
        var temp = confirm('是否确定删除');
        if (temp == false) {
            return false;
        }
        $(this).closest("li").remove();
    });
    new_jq_ele.find(".default").on("mousedown", function () {//设置默认图片
        $(".main_img .default").removeAttr('style');
        $(this).attr('style','color:#88CE20');
        $("input[name^=default]").val(0);
        $("input[name='default["+idx+"]']").val(1);
    });
    new_jq_ele.insertBefore($(ele_li));
    return new_jq_ele;
}
//图片上传
$(function () {
    $('input[name=imagefield]').click(function(){
        var image_list = [];
        var n = 0;
        $("input[name^=images]").each(function(i){
            if(this.value !=''){
                image_list[i] = this.value;
                n++;
            }
        });
        if (n > 4) {
            layer.alert('打款凭证最多上传五张');return false;
        }
        $('#fileupload').click();
    });
    var swiper = new Swiper('.swiper-container', {
        pagination: '.swiper-pagination',
        slidesPerView: 5,
        paginationClickable: true,
        spaceBetween: 10,
        freeMode: true
    });
    var bar = $('.bar');
    var percent = $('.percent');
    var progress = $(".progress");
    var files = $(".files");
    var files_details = $(".files_details");
    var btn = $(".btn_");
    var btn_details = $(".btn_details");
    $("#fileupload").wrap("<form id='myupload' action='/image/upload-image' method='post' enctype='multipart/form-data'></form>");
    $("#fileupload").change(function(){
        var ele_parent = panel + ".goods_image ",
            li_last = ele_parent + "li:last ",
            image_last = ele_parent + ".real_images:last ";
        var index = layer.msg('上传中...', {icon: 16,shade: [0.5, '#f5f5f5'],scrollbar: false,offset: '0px', time:1000000}) ;
        $("#myupload").ajaxSubmit({
            data:{'type':'product_img'},
            dataType:  'json',
            beforeSend: function() {
            },
            uploadProgress: function(event, position, total, percentComplete) {
            },
            success: function(res) {
                var data = res.result;
                layer.close(index);
                $(image_last).removeClass('hidden');
                var img = "http://xianyongta.oss-cn-shanghai.aliyuncs.com/files/" + data.pic;
                $(image_last + "img").attr("src", img);
                $(image_last + "input[name^=images]").val('files/'+data.pic);
            },
            error:function(xhr){
                layer.close(index);
                btn.html("上传失败");
                bar.width('0');
                files.html(xhr.responseText);
            }
        });
    });
});

//重新生成预览
IsFireFox = function () {
    var ua = "" + navigator.userAgent;
    if (ua.toLowerCase().indexOf("firefox") > 0) {
        return true;
    }
    return false;
}

/**
 * 保存数据
 * @returns {boolean}
 */
function save() {
    var product_name = $("#product_name").val();  // 奖品名称
    var text_description = $('#text_description').val();//奖品描述
    var type = $("#type").val();//奖池分类
    var total_num = $("#total_num").val();  // 奖品数量
    var portrait = $('#portrait_show').attr('src'); // 客户头像

    if (!product_name) {
        layer.alert('请输入奖品名称');
        return false;
    }
    if (!text_description) {
        layer.alert('请输入奖品描述!');
        return false;
    }
    if (!type) {
        layer.alert('请选择奖池!');
        return false;
    }
    if (!total_num) {
        layer.alert('请输入奖品数量!');
        return false;
    }
    if (!portrait) {
        layer.alert('请上传奖品图片!');
        return false;
    }
    $.ajax({
        type: 'post',
        url: '/product/insert',
        data: {
            'product_name': product_name,
            'text_description': text_description,
            'type':type,
            'total_num':total_num,
            'portrait': portrait
        },
        beforeSend: function () {
            var index = layer.msg('奖品添加中...', {
                icon: 16,
                shade: [0.5, '#f5f5f5'],
                scrollbar: false,
                offset: '0px',
                time: 1000000
            });
        },
        dataType: 'json',
        success: function (response) {
            if (response.code == 200) {
                layer.alert(response.message, function () {
                    window.location.href = '/product/index';
                    return false;
                });
            } else {
                $(".save_product").attr("disabled", false);
                layer.alert(response.message, function () {
                    layer.closeAll();
                });
                return false;
            }
        }
    });
}

/**
 * 更新数据
 * @returns {boolean}
 */
function update() {
    var product_id = $("#product_id").val(); //奖品id
    var product_name = $("#product_name").val();  // 奖品名称
    var brand_id = $("#brand").val(); // 分类id
    var unit_id = $("#unit").val(); // 计量单位
    // var standard_name = $("#standard_name").val(); // 规格名称
    // var standard_num = $("#standard_num").val(); // 规格进率
    var standard_string = $("#standard_string").val(); // 规格进率
    var status = $("#status").val(); // 订单状态
    var sell_status = $("#sellstatus").val(); // 是否可售
    if(!sell_status){
        layer.alert("请选择是否售卖");
        return false;
    }
    var product_sku = []; // 奖品属性
    var text_description = $('#text_description').val();
    var rich_description = UM.getEditor('rich_description').getContent();  // 富文本内容;
    var product_image_list = [];
    var rank_recommend = {};
    var channel_id = $("#channel").val();  //  渠道id
    if (!brand_id) {
        layer.alert('请选择奖品分类');
        return false;
    }
    if (!product_name) {
        layer.alert('请输入奖品名称');
        return false;
    }
    if (!unit_id) {
        layer.alert('请选择基础计量单位!');
        return false;
    }
    $("input[name^=images]").each(function (i) {
        if (this.value != '') {
            product_image_list[i] = this.value;
        }
    });
    // 判断是否有图片
    if (product_image_list.length == 0) {
        layer.alert('请上传奖品图片！');
        return false;
    }
    //奖品默认图片数组
    var image_default_list = [];
    var is_default = 0;
    $("input[name^='default']").each(function (i) {
        if (this.value == 1) {
            is_default += 1;
        }
        if (this.value != "") {
            image_default_list[i] = this.value;
        }
    });
    if (count(product_image_list) > 5) {
        layer.alert('产品图片最多上传五张');
        return false;
    }
    if (is_default > 1) {
        layer.alert('默认图片只能选择一张！');
        return false;
    }
    if (is_default == 0) {
        layer.alert('请选择默认图片！');
        return false;
    }
    var hasattr_tbody_ele = $('.hasattr').find('tbody');
    var attrnum, attrname, attrval;
    var no_complete_cost = false;
    var no_complete_stock = false;
    var no_complete_sell_prise = false;
    var onedata_cost = false;
    var onedata_sell_price = false;

    hasattr_tbody_ele.each(function () {
        if (!$(this).hasClass('tbody_recommend')) {
            var onedata = {};
            var attr = {};
            var rank_price = {};
            var basic = {};
            $(this).find('.attrsku').each(function () {
                attrnum = $(this).attr('attrnum');
                attrname = $(this).parent().parent().parent().find('.' + attrnum).text();
                attrval = $(this).text();
                attr[attrname] = attrval;
            });
            $(this).find('.rank-price').each(function () {
                var rank_id = $(this).attr('rank_id');
                var rank_price_input = $(this).val();
                rank_price[rank_id] = rank_price_input;
            });
            basic['product_sku_id'] = $(this).find('input[name="product_sku_id"]').val();
            basic['cost'] = $(this).find('input[name="cost"]').val();
            basic['price'] = $(this).find('input[name="price"]').val();
            basic['sku_code'] = $(this).find('input[name="sku_code"]').val();
            basic['minimum_order'] = $(this).find('input[name="minimum_order"]').val();
            basic['sale_status'] = $(this).find('input[name^="sale_status_"]:checked').val(); // 售卖状态
            if (basic['cost'] == '' || isNaN(basic['cost'])) {
                no_complete_cost = true;
                return false;
            }
            if (basic['cost'] <= '0') {
                onedata_cost = true;
                return false;
            }
            if (basic['price'] == '' || isNaN(basic['price'])) {
                no_complete_sell_prise = true;
                return false;
            }
            if (onedata['price'] <= '0') {
                onedata_sell_price = true;
                return false;
            }
            onedata['attr'] = attr;
            onedata['rank_price'] = rank_price;
            onedata['basic'] = basic;
            product_sku.push(onedata);
        } else {
            //这个只有一遍
            $(this).find('.rank-recommend').each(function () {
                var rank_id = $(this).attr('rank_id');
                var rank_price_input = $(this).val();
                rank_recommend[rank_id] = rank_price_input;
            });
        }
    });
    if (onedata_cost == true) {
        layer.alert('单位成本价不能小于等于0');
        return false;
    }
    if (onedata_sell_price == true) {
        layer.alert('计量单位售价不能小于等于0');
        return false;
    }
    if (no_complete_cost == true) {
        layer.alert('请完善各属性成本价，成本价为数值');
        return false;
    }
    if (no_complete_sell_prise == true) {
        layer.alert('请完善各属性售价，售价需为数值');
        return false;
    }
    $.ajax({
        type: 'post',
        url: '/product/update',
        data: {
            'product_id': product_id,
            'product_name': product_name,
            'brand_id': brand_id,
            'unit_id': unit_id,
            // 'standard_name': standard_name,
            // 'standard_num': standard_num,
            'standard_string':standard_string,
            'status': status,
            'sell_status':sell_status,
            'product_sku': product_sku,
            'rank_recommend': rank_recommend,
            'text_description': text_description,
            'rich_description': rich_description,
            'product_image_list': product_image_list,
            'channel_id':channel_id,
            'image_default_list':image_default_list
        },
        beforeSend: function () {
            var index = layer.msg('奖品更新中...', {
                icon: 16,
                shade: [0.5, '#f5f5f5'],
                scrollbar: false,
                offset: '0px',
                time: 1000000
            });
        },
        dataType: 'json',
        success: function (response) {
            if (response.code == 200) {
                layer.alert(response.message, function () {
                    window.history.back();
                    return false;
                });
            } else {
                $(".save_product").attr("disabled", false);
                layer.alert(response.message, function () {
                    layer.closeAll();
                    window.location.reload();
                });
                return false;
            }
        }
    });
}
/**
 * 取对象个数
 * @param o
 * @returns {*}
 */
function count(o) {
    var t = typeof o;
    if (t == 'string') {
        return o.length;
    } else if (t == 'object') {
        var n = 0;
        for (var i in o) {
            n++;
        }
        return n;
    }
    return false;
}

/**
 * 单位改变的时候改变规格名称
 */
$("#unit").on('change', function () {
    if ($("#unit").val()) {
        var unit_name = $("#unit :selected").text();
        $("#unit_name").html(unit_name);
    }
});